package queuedemo;

//利用数组设计循环队列
public class MyCircularQueue {

    public int[] elem;
    public int front;
    public int rear;

    public MyCircularQueue(int k) {
        //构造方法进行数组初始化
        this.elem = new int[k];
    }

    /**
     * 入队操作
     *
     * @param value
     * @return
     */
    public boolean enQueue(int value) {
        if (isFull()) {
            return false;
        }
        elem[rear] = value;
        //例如  (k - 1 + 1) % k = 0
        rear = (rear + 1) % elem.length;
        return true;
    }

    /**
     * 出队操作
     *
     * @return
     */
    public boolean deQueue() {
        //先判断空不空
        if (isEmpty()) {
            return false;
        }
        front = (front + 1) % elem.length;
        return true;
    }

    /**
     * 得到队头元素，不删除
     * @return
     */
    public int Front() {
        //先判断空不空
        if (isEmpty()) {
            return -1;
        }
        return elem[front];
    }

    /**
     * 得到队尾元素，不删除
     * @return
     */
    public int Rear() {
        //先判断空不空
        if (isEmpty()) {
            return -1;
        }
        int index = (rear == 0) ? elem.length - 1 : rear - 1;
        return elem[index];
    }

    public boolean isEmpty() {
        return front == rear;
    }

    /**
     * 判断是否满了
     *
     * @return
     */
    public boolean isFull() {
        return (rear + 1) % elem.length == front;
    }
}
